<!DOCTYPE html>
<html lang="en">
<head>
    <title>人脸验证登录</title>
    <meta charset="utf-8">
	<script src="@{/static/layui/js/jquery.min.js}" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<button onclick="openMedia()">开始人脸识别</button>
<video id="video" width="500px" height="500px" autoplay="autoplay"></video>
<canvas id="canvas" width="500px" height="500px"></canvas>

<script>
    let mediaStreamTrack=null; // 视频对象(全局)
    let video ;
		//调用摄像头展示到页面然后5s后拍照
    function openMedia() {
        let constraints = {
            video: { width: 500, height: 500 },
            audio: false
        };
        //获得video摄像头
         video = document.getElementById('video');     
        let promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then((mediaStream) => {
           // mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1];
           mediaStreamTrack=mediaStream.getVideoTracks()
            video.srcObject = mediaStream;
            video.play();
        });
				//定时拍照 并ajax到后台
				   setTimeout(function(){
				       //获得Canvas对象
				       let video = document.getElementById('video');
				       let canvas = document.getElementById('canvas');
				       let ctx = canvas.getContext('2d');
				       ctx.drawImage(video, 0, 0, 500, 500);
								closeMedia();
				       // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
				       let img = document.getElementById('canvas').toDataURL("image/jgp");
								//去除 data URL 中的头部说明
				       console.log('img-----', img);
				       //document.getElementById('imgTag').src=img;//上传
				　　　　$.ajax({
															url:"http://localhost/face",
															type:"POST",
															data:{"imgData":img}        	　　　　　　　　
															,success:function(data){
																console.log(data);        		　　　　　　　　
																document.gauges.forEach(function(gauge) {        			　　　　　　　　
																			gauge.value =data.data        		　　　　　　
																	});        	　　　　　　
																}        	　　　　　　
																,error:function(){
																console.log("服务端异常！");        	　　　　　　
																}        　　　　　　
																});
																
				   },5000);
				
    }
    // 关闭摄像头
    function closeMedia() {
          let stream = document.getElementById('video').srcObject;
          let tracks = stream.getTracks();
          tracks.forEach(function(track) {
            track.stop();
          });
         document.getElementById('video').srcObject = null;
    }
</script>
</body>